package net.lab1024.sa.admin.interceptor;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.strategy.SaAnnotationStrategy;
import cn.dev33.satoken.strategy.SaStrategy;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.common.DateTimeUtils;
import net.lab1024.sa.admin.config.UserContextHolder;
import net.lab1024.sa.admin.module.business.category.domain.entity.UserContext;
import net.lab1024.sa.admin.module.business.category.service.UserCacheService;
import net.lab1024.sa.admin.module.system.login.domain.RequestEmployee;
import net.lab1024.sa.admin.module.system.login.domain.RequestLoginUser;
import net.lab1024.sa.admin.module.system.login.service.LoginService;
import net.lab1024.sa.base.common.annoation.NoNeedLogin;
import net.lab1024.sa.base.common.code.SystemErrorCode;
import net.lab1024.sa.base.common.code.UserErrorCode;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.util.SmartRequestUtil;
import net.lab1024.sa.base.common.util.SmartResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Enumeration;
import java.util.Map;

/**
 * admin 拦截器
 *
 * @Author 1024创新实验室-主任:卓大
 * @Date 2023/7/26 20:20:33
 * @Wechat zhuoda1024
 * @Email lab1024@163.com
 * @Copyright <a href="https://1024lab.net">1024创新实验室</a>，Since 2012
 */

@Component
@Slf4j
public class AdminInterceptor implements HandlerInterceptor {

    @Resource
    private LoginService loginService;

    @Autowired
    private UserCacheService userCacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("mark");
        if (StpUtil.isLogin()) {
            String userId = StpUtil.getLoginIdAsString();
            UserContext userContext = userCacheService.getCachedUser(userId);

            if (userContext != null) {
                UserContextHolder.setUserContext(userContext);
            }
        }

        // OPTIONS请求直接return
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return false;
        }

        boolean isHandler = handler instanceof HandlerMethod;
        if (!isHandler) {
            return true;
        }

        try {
            log(request);
            // --------------- 第一步： 根据token 获取用户 ---------------
            LocalDateTime localDateTime = LocalDateTime.now();
            log.info("1 Header入参,time:{} header:{}", DateTimeUtils.getStrDateTime(localDateTime), request.getHeader("Authorization"));

            // 1. 检查登录状态
            if (!StpUtil.isLogin()) {
                log.info("1 未登录或Token已过期");
            }

            // 2. 获取Token（可选，通常直接使用StpUtil.getLoginId()）
            String token = StpUtil.getTokenValue();
            if (token == null) {
                log.info("1 请求中未携带有效Token");
            }

            String tokenValue = StpUtil.getTokenValue();
            log.info("1 getTokenValue,结果 tokenValue:{}", tokenValue);
            String loginId = (String) StpUtil.getLoginIdByToken(tokenValue);
            //RequestEmployee requestEmployee = loginService.getLoginEmployee(loginId, request);
            log.info("2 getLoginUser开始,入参loginId:{}", loginId);
            RequestLoginUser loginUser = loginService.getLoginUser(loginId, request);
            log.info("2  getLoginUser结束,结果 loginUser{}", loginUser);
            // --------------- 第二步： 校验 登录 ---------------

            Method method = ((HandlerMethod) handler).getMethod();
            NoNeedLogin noNeedLogin = ((HandlerMethod) handler).getMethodAnnotation(NoNeedLogin.class);
            if (noNeedLogin != null) {
                checkActiveTimeout(loginUser);
                return true;
            }

            if (loginUser == null) {
                SmartResponseUtil.write(response, ResponseDTO.error(UserErrorCode.LOGIN_STATE_INVALID));
                return false;
            }

            // 检测token 活跃频率
            checkActiveTimeout(loginUser);

            // --------------- 第三步： 校验 权限 ---------------

            SmartRequestUtil.setRequestUser(loginUser);
            if (SaAnnotationStrategy.instance.isAnnotationPresent.apply(method, SaIgnore.class)) {
                return true;
            }

            // 如果是超级管理员的话，不需要校验权限
            if (loginUser.getAdministratorFlag()) {
                return true;
            }

            SaAnnotationStrategy.instance.checkMethodAnnotation.accept(method);

        } catch (SaTokenException e) {
            /*
             * sa-token 异常状态码
             * 具体请看： https://sa-token.cc/doc.html#/fun/exception-code
             */
            int code = e.getCode();
            if (code == 11041 || code == 11051) {
                SmartResponseUtil.write(response, ResponseDTO.error(UserErrorCode.NO_PERMISSION));
            } else if (code == 11016) {
                SmartResponseUtil.write(response, ResponseDTO.error(UserErrorCode.LOGIN_ACTIVE_TIMEOUT));
            } else if (code >= 11011 && code <= 11015) {
                SmartResponseUtil.write(response, ResponseDTO.error(UserErrorCode.LOGIN_STATE_INVALID));
            } else {
                SmartResponseUtil.write(response, ResponseDTO.error(UserErrorCode.PARAM_ERROR));
            }
            return false;
        } catch (Throwable e) {
            SmartResponseUtil.write(response, ResponseDTO.error(SystemErrorCode.SYSTEM_ERROR));
            log.error(e.getMessage(), e);
            return false;
        }

        // 通过验证
        return true;
    }


    private void log(HttpServletRequest request) {
        // 1. 打印基础请求信息
        log.info(StringUtils.repeat("\n", 50) + "=== log from preHandle begin===");
        log.info("\n=== 请求拦截日志 ===");
        log.info("URL: " + request.getRequestURL());
        log.info("HTTP Method: " + request.getMethod());
        log.info("Remote IP: " + request.getRemoteAddr());

        // 2. 打印所有 Headers
        log.info("\n--- Headers ---");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            log.info(headerName + ": " + request.getHeader(headerName));
        }

        // 3. 打印请求参数（Query Params 或 Form Data）
        log.info("\n--- Parameters ---");
        Map<String, String[]> params = request.getParameterMap();
        params.forEach((key, value) -> log.info(key + ": " + String.join(",", value)));

        // 4. 打印 Sa-Token 信息
        log.info("\n--- Sa-Token Info ---");
        String tokenValue = StpUtil.getTokenValue();
        log.info("Token from StpUtil: " + tokenValue);
        log.info("Is Login: " + StpUtil.isLogin());
        log.info("Login ID: " + StpUtil.getLoginIdDefaultNull());

        // 5. 检查 Token 是否在请求中存在（但未被 Sa-Token 识别）
        String authHeader = request.getHeader("Authorization");
        String cookieToken = getCookieValue(request, "satoken"); // 默认 Token 名称
        log.info("Authorization Header: " + authHeader);
        log.info("Cookie Token (satoken): " + cookieToken);
        log.info("=== log from preHandle end===" + StringUtils.repeat("\n", 50));
    }


    // 辅助方法：从 Cookie 中获取指定名称的值
    private String getCookieValue(HttpServletRequest request, String name) {
        if (request.getCookies() == null) return null;
        for (javax.servlet.http.Cookie cookie : request.getCookies()) {
            if (name.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

    /**
     * 检测：token 最低活跃频率（单位：秒），如果 token 超过此时间没有访问系统就会被冻结
     */
    private void checkActiveTimeout(RequestEmployee requestEmployee) {
        // 用户不在线，也不用检测
        if (requestEmployee == null) {
            return;
        }

        StpUtil.checkActiveTimeout();
        StpUtil.updateLastActiveToNow();
    }

    private void checkActiveTimeout(RequestLoginUser requestLoginUser) {
        // 用户不在线，也不用检测
        if (requestLoginUser == null) {
            return;
        }

        StpUtil.checkActiveTimeout();
        StpUtil.updateLastActiveToNow();
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.clear();
        // 清除上下文
        SmartRequestUtil.remove();
    }
}